package com.cloudbroker.bcs.platform.dav.middle.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;



public class SSLHttpUtil {

    private static final Logger LOG = LoggerFactory
            .getLogger(SSLHttpUtil.class);
    
    private static SSLContext sslCtx = null;
    static {
        
        try {
            sslCtx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                }
                
                public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                }
                
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslCtx.init(null, new TrustManager[] { tm }, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                // TODO Auto-generated method stub
                return true;
            }
            
        });
        
        if(null != sslCtx){
            HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
        } 
    }
    
    // 设置body体
    public static void setBodyParameter(StringBuilder sb, HttpURLConnection conn) throws IOException {
        String requestBody = sb.toString();
        System.out.println("Rong Clound Request Parameter : " + requestBody);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(requestBody);
        out.flush();
        out.close();
    }
    
    public static HttpURLConnection createJsonPostHttpConnection( String uri) throws MalformedURLException,
            IOException, ProtocolException {
        return createPostHttpConnection( uri, "application/json");
    }
    
    public static void setBodyParameter(String str, HttpURLConnection conn) throws IOException {
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(str.getBytes("utf-8"));
        out.flush();
        out.close();
    }
    
    private static HttpURLConnection createPostHttpConnection(String uri, String contentType)
            throws MalformedURLException, IOException, ProtocolException {

        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setInstanceFollowRedirects(true);
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        conn.setRequestProperty("Content-Type", contentType);
        
        return conn;
    }
    
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
    
    public static String returnResult(HttpURLConnection conn) throws Exception, IOException {
        String result;
        InputStream input = null;
        if (conn.getResponseCode() == 200) {
            input = conn.getInputStream();
        } else {
            input = conn.getErrorStream();
        }
        result = new String(readInputStream(input), "UTF-8");
        System.out.println("Result from Rong Cloud " + result.toString());
        return result;
    }

    public static String doPostJson(String url, String json) {
        String result=null;
        InputStream input = null;
        try {
            HttpURLConnection conn = createJsonPostHttpConnection(url);
            setBodyParameter(json, conn);
            if (conn.getResponseCode() == 200) {
                input = conn.getInputStream();
                result = new String(readInputStream(input), "UTF-8");
                return  result;
            }else{
                input = conn.getErrorStream();
                LOG.error("接口服务器返回值出错，错误码：" + conn.getResponseCode()
                        + "，错误信息：" +   new String(readInputStream(input), "UTF-8"));
            }
        }catch (Exception e){
            LOG.error("接口服务器请求出错，错误信息：",e);
            return null;
        }
        return result;
    }
}
